package springcloud.consume.controller;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import springcloud.service.model.User;

import java.util.List;
import java.util.Map;

/**
 * 消费端接口，像 eureka 请求需要的服务
 */
@RestController
@Slf4j
@RefreshScope
@RequestMapping("/consume")
public class ConsumeController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 调用服务提供者接口名称，此接口会调用到 eureka.client.serviceUrl.defaultZone 配置的 http://192.168.2.126:6110/eureka/,http://192.168.2.131:6111/eureka/
     * 注册中心上面注册的 SPRINGCLOUD-SERVICE 服务提供者上面
     */
    private String eurekaService = "http://SPRINGCLOUD-SERVICE";

    @Value("${source}")
    private String source;
    @Value("${name}")
    private String name;

    @ResponseBody
    @PostMapping("/addUser")
    public int addUser(User user){

        log.info("===============${name}=" + name);
        log.info("===============${source}=" + source);
        log.debug("===============addUser");

        Map map = BeanUtil.beanToMap(user);
        int i = restTemplate.postForObject(eurekaService + "/user/addUser/", map, Integer.class);
        return i;
    }

    @ResponseBody
    @GetMapping("/getUserById/{userId}")
    public User getUserById(@PathVariable("userId") Integer userId){

        log.info("===============${name}=" + name);
        log.info("===============${source}=" + source);
        log.debug("===============addUser");

        User user = restTemplate.getForObject(eurekaService + "/user/getUserById/" + userId, User.class);

        return user;
    }

    @ResponseBody
    @GetMapping("/getAll")
    public List<User> getAll(){

        log.info("===============${name}=" + name);
        log.info("===============${source}=" + source);
        log.debug("===============getAll");

        List<User> user = restTemplate.getForObject("http://SPRINGCLOUD-SERVICE/user/getAll", List.class);

        return user;
    }
}



